package com.neuedu.aop;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

/**
 * @Author: MARK
 * @Date: 2019/7/26 16:02
 * @version: 1.0.0
 * @Description:
 */
//将切面类加载到容器中
@Component
//标注该类是切面类
@Aspect
@Slf4j
public class exeTimeAop {
    //定义切入点
    @Pointcut("execution(* com.neuedu.*..*(..))")
    private void anyMethod(){}

    @Before("anyMethod()")
    public void before(){

    }
    //环绕通知, 参数为切入点
    //如果后续要写返回值通知，这里需要返回运行结果obj
    //如果后续需要异常通知，这里需要抛出异常，让异常通知捕获
    @Around("anyMethod()")
    public Object aroundMethod(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        long start = System.currentTimeMillis();
        Object obj = proceedingJoinPoint.proceed();

        long end = System.currentTimeMillis()-start;
        Object[] args = proceedingJoinPoint.getArgs();
        String json = JSON.toJSONString(args);

        log.info("类："+proceedingJoinPoint.getTarget().getClass().getName()+"\n的方法"+proceedingJoinPoint.getSignature().getName()
                +"\n参数为"+json+"\n执行时间为"+end/1000.0+"s");
        return obj;

    }
    //返回值通知
    @AfterReturning(value = "anyMethod()", returning = "result")
    public void afterMethod(Integer result){
        log.info(result+"");
    }
    //异常通知
    @AfterThrowing(value = "anyMethod()", throwing = "ex")
    public void throwingMethod(Exception ex){
        log.info("------"+ex.getMessage());
    }
}
